package case20

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"time"
)

func Test() {

	fmt.Println("🎯示例二十：Cookie")

	r := gin.Default()

	// 获取 cookie
	r.GET("/cookie", func(c *gin.Context) {
		authCookie, err := c.Cookie("auth_cookie")
		if err != nil {
			var timestamp int64 = time.Now().UnixMilli() //毫秒级时间戳
			authCookie = fmt.Sprint(timestamp)           //cookie 赋值
			// c.SetCookie() 设置参数：
			//name: Cookie 名称
			//value: Cookie 值
			//maxAge: 生存时间，单位秒；负数表示浏览器关闭时删除
			//path: 路径，默认为 /
			//domain: 所属域名
			//secure: 是否只在 HTTPS 下传输
			//httpOnly: 是否禁止 JavaScript 访问此 Cookie
			c.SetCookie("auth_cookie", authCookie, 3, "/", "localhost", false, true)

			// ✨安全的 Cookie 设置示例
			//c.SetCookie("session_id", sessionId, 3600, "/", "example.com", true, true)
		}

		c.JSON(200, gin.H{
			"auth_cookie": authCookie,
		})
	})

	// 删除cookie
	r.DELETE("cookie", func(c *gin.Context) {

		// 删除cookie
		c.SetCookie("auth_cookie", "", -1, "/", "localhost", false, true)
		c.JSON(200, gin.H{
			"message": "ok",
		})
	})

	r.Run(":60000")

}
